/**
 * ImageWorker.java  [V 1.0.0]
 * zhangyw Create at 2014年8月11日 下午3:47:14
 */
package com.zyw.utils;

import java.lang.ref.WeakReference;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;


/**
 * 我们把具体的异步读取图片资源的操作方法都放在这里。 由他来处理图片的初始化
 * 
 * @author zhangyw create at 2014年8月11日 下午3:47:14
 */
public class ImageWorker {
  private static final String TAG = "ImageWorker";
  private ImageCache mImageCahe;
  private int defaultWidth;
  private int defaultHeight;
  private final ThreadFactory sThreadFactory = new ThreadFactory() {
    private final AtomicInteger mCount = new AtomicInteger(1);

    public Thread newThread(Runnable r) {
      return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
    }
  };
  //一个worker用一个线程池处理器就行了，不用每次load的时候，去创建一个
  private final Executor DUAL_THREAD_EXECUTOR = Executors.newFixedThreadPool(2, sThreadFactory);
  /**
   * The actual AsyncTask that will asynchronously process the image.
   */

  private class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
    private final WeakReference<ImageView> imageViewReference;

    public BitmapWorkerTask(ImageView imageView) {
      imageViewReference = new WeakReference<ImageView>(imageView);

    }

    /*
     * (non-Javadoc) 在其他线程加载图像
     * 还需要考虑强制取消任务的情况
     * 
     * @param params 第一个参数表示图片文件地址
     * @see android.os.AsyncTask#doInBackground(java.lang.Object[])
     */
    @Override
    protected Bitmap doInBackground(String... params) {
      String picPath = params[0];
      Bitmap rtnData = null;
      if (picPath != null) {
        if (mImageCahe != null) {
          rtnData = mImageCahe.getBitmapFromDiskCache(picPath);
        }
        if(rtnData!=null){
          Log.v(TAG, "have got bitmap from diskcache");
        }else if (imageViewReference.get() != null) {
          rtnData = PicUtils.getRightBitmap(picPath, imageViewReference.get(), defaultWidth, defaultHeight);
        }
        mImageCahe.addBitmap2Cache(picPath, rtnData);
      }
      return rtnData;
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
     */
    @Override
    protected void onPostExecute(Bitmap result) {
      super.onPostExecute(result);
      ImageView tmp = imageViewReference.get();
      if (tmp != null) {
        tmp.setImageBitmap(result);
      }
    }
  }

  public ImageWorker(Context context,int defaultWidth, int defaultHeight){
    if(null==ImageCache.getContext()){
      //避免重复操作
      ImageCache.setContext(context);
    }
    mImageCahe= ImageCache.getInstance();
    this.defaultHeight=defaultHeight;
    this.defaultWidth=defaultWidth;
  }
  
  /**
   * 把异步处理image设置的任务都放在这里， 包括是从cache中取出还是要解码 1.从内存cache中读取
   * 2.从diskcache中解码（此部分异步处理） 3.异步从元数据中解码
   * 
   * @author zhangyw
   * @param imageView
   * @param filename
   */
  public void loadImage(ImageView imageView, String filename) {
    Bitmap tmp = null;
    if (mImageCahe != null) {
      tmp = mImageCahe.getBitmapFromMemCache(filename);
    }
    if (tmp != null) {
      Log.v(TAG, "have got bitmap from memcache");
      imageView.setImageBitmap(tmp);
    } else {
      final BitmapWorkerTask bitmapWorkerTask = new BitmapWorkerTask(imageView);
      bitmapWorkerTask.executeOnExecutor(DUAL_THREAD_EXECUTOR, filename);
    }
  }

}
